import base64
import hashlib
import json
import requests
import time, datetime
from functools import wraps


class pre_api_get:
    def __init__(self):
        self.appkey = 'Jq2EdAyFTV8ossckCNOy'
        self.appSecret = 'zRDYitIXAFHmXTWp4iY3pDw9gpDcMx2RhJxG51WV'
        self.openid = 'Wa6bPNzmLGEVbW5gySjQ'

        self.api = 'https://gateway.rjmart.cn/open/shop'
        self.pre_api = 'https://gateway.test.rj-info.com/open/shop'

    # 获取Authorization_Code
    def get_Authorization_Code(self):
        url = 'https://www.rjmart.cn/auth/oauth/authorize'
        response = requests.get(url=url)
        return response

    # 通过Authorization_Code获取Access_Token
    def ac_get_Access_Token(self):
        url = 'https://www.rjmart.cn/auth/oauth/token'
        response = requests.post(url=url)
        return response

    # 通过openid获取Access_Token
    def openid_Access_Token(self):
        url = 'https://www.rjmart.cn/auth/openid/login'
        md5 = hashlib.md5()
        md5.update(self.appSecret.encode('utf-8'))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        data = {'openid': self.openid, 'sign': sign}
        response = requests.post(url=url, data=data)
        results = json.loads(response.content.decode('utf-8'))
        t = time.time()
        results.update({'time': t})
        with open('Access_Token_xr.json', mode='w') as f:
            f.write(json.dumps(results))
        # with open('main_dir/Access_Token.json', mode='w') as f2:
        #     f2.write(json.dumps(results))
        return results

    # api基础模板
    def no_data(self, url, name, data=""):
        time_now = time.time()
        with open('Access_Token_xr.json') as j:
            ac_json = json.load(j)
        Access_Token = ac_json['access_token']
        time_acc = ac_json['time']
        if time_now - time_acc > 600:
            Access_Token = self.openid_Access_Token()['access_token']
        header = {'Authorization': f'Bearer {Access_Token}',
                  'Content-Type': 'application/json;charset=utf-8'}
        json_post_data = self.appSecret + data
        # data = json.loads(data)
        md5 = hashlib.md5()
        md5.update(json_post_data.encode('utf-8'))  # 指定需要加密的字符串
        sign = md5.hexdigest()  # 加密后的字符串
        s_url = f'{self.api}{url}?appkey={self.appkey}&sign={sign}'
        # print(s_url)
        response = requests.post(url=s_url, data=data.encode('utf-8'), headers=header)
        results = response.content.decode('utf-8')
        with open(f'{name}.json', mode='w', encoding='utf-8') as f:
            f.write(results)
        return response

    # 查询所有运费模板
    def findTemplate(self):
        url = '/openapi/product/findTemplate'
        name = 'findTemplate'
        return self.no_data(url, name)

    # 查询商品标准单位与规格
    def UnitAndSpec(self):
        url = '/openapi/product/queryUnitAndSpecification'
        name = 'UnitAndSpec'
        return self.no_data(url, name)

    # 查询入驻单位
    def settledOgrList(self):
        url = '/openapi/product/settledOgrList'
        name = 'settledOgrList'
        return self.no_data(url, name)

    # 商品树形分类查询
    def AllCategoryTree(self):
        url = '/openapi/product/queryAllCategoryTree'
        name = 'AllCategoryTree'
        return self.no_data(url, name)

    # 商品品牌查询
    def getSuppBrands(self):
        url = '/openapi/product/getSuppBrands'
        name = 'getSuppBrands'
        return self.no_data(url, name)

    # 查询商品一级分类的属性（一级分类Id）
    def CategoryAttribute(self, categoryId):
        url = '/openapi/product/queryCategoryAttribute'
        name = 'CategoryAttribute' + str(categoryId)
        data = json.dumps({"categoryId": categoryId})
        return self.no_data(url, name, data=data)

    # 批量查询商品（"status" : 3,      2:草稿，3:上架，4下架，5强制下架，12待审核，15已驳回
    #     "brandIds" : [2],         品牌列表
    #     "categoryId" : 1671,      分类id
    #     "productNum" : "202200",  商品货号
    #     "productName" : "测试商品"） 商品名
    def ProductList(self, page, add_data="{}"):
        url = '/openapi/product/queryProductList'
        data = {"page": page, "size": 100}
        data.update(json.loads(add_data))
        name = 'ProductList' + '&'.join(list(map(str, data['brandIds'])))
        return self.no_data(url, name, data=json.dumps(data))

    # 查询单个商品内容（id）
    def ProductDetail(self, ProductId):
        url = '/openapi/product/queryProductDetail'
        name = 'ProductDetail' + str(ProductId)
        data = json.dumps({"id": ProductId})
        return self.no_data(url, name, data=data)

    # 上架商品（id_list/code_list）
    def onSale(self, ProductId_list):
        url = '/openapi/product/onSale'
        name = 'onSale'
        data = json.dumps({"productIdList": ProductId_list})
        return self.no_data(url, name, data=data)

    # 删除商品（id_list/code_list）
    def deleteProduct(self, ProductCode_list):
        url = '/openapi/product/deleteProductList'
        name = 'deleteProductList'
        data = json.dumps({"productCodeList": ProductCode_list})
        return self.no_data(url, name, data=data)

    # 下架商品（id_list/code_list）
    def offSale(self, ProductId_list):
        url = '/openapi/product/offShelves'
        name = 'offSale'
        data = json.dumps({"productCodeList": ProductId_list})
        return self.no_data(url, name, data=data)

    # 撤销商品审核（id_list/code_list）
    def cancelReview(self, ProductId_list):
        url = '/openapi/product/cancelReview'
        name = 'cancelReview'
        data = json.dumps({"productIdList": ProductId_list})
        return self.no_data(url, name, data=data)

    # 单个新增、更新
    def saveOrUpdateProduct(self, json_data):
        url = '/openapi/product/saveOrUpdateProduct'
        name = 'saveOrUpdateProduct'
        return self.no_data(url, name, data=json_data)

    # 批量新增、更新
    def batchSaveOrUpdateProduct(self, json_data):
        url = '/openapi/product/batchSaveOrUpdateProduct'
        name = 'saveOrUpdateProduct'
        return self.no_data(url, name, data=json_data)

    # 批量更新（可部分更新）
    def updateProductInfoByCode(self, json_data):
        url = '/openapi/product/updateProductInfoByCode'
        name = 'updateProductInfoByCode'
        return self.no_data(url, name, data=json_data)


if __name__ == '__main__':
    rj_api = pre_api_get()
    # 先获取Token(已内置）
    rj_api.openid_Access_Token()
    # 对接
    responses = rj_api.findTemplate()
    result = responses.content.decode('utf-8')
    print(responses)
    print(result)
